package com.rickpan.controller;

import com.rickpan.dto.request.TeamMessageRequest;
import com.rickpan.dto.response.TeamMessageDTO;
import com.rickpan.entity.TeamMessage;
import com.rickpan.service.TeamMessageService;
import com.rickpan.utils.SecurityUtils;
import com.rickpan.dto.common.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 团队消息控制器
 * 
 * @author 开发团队协调员
 * @since 2025-07-16
 */
@RestController
@RequestMapping("/api/teams/{teamId}/messages")
@Tag(name = "团队消息", description = "团队聊天室消息管理接口")
public class TeamMessageController {

    private static final Logger logger = LoggerFactory.getLogger(TeamMessageController.class);

    @Autowired
    private TeamMessageService teamMessageService;

    /**
     * 发送团队消息
     */
    @PostMapping
    @Operation(summary = "发送团队消息", description = "发送文本、图片或文件消息到团队聊天室")
    public ApiResponse<TeamMessageDTO> sendMessage(
            @Parameter(description = "团队ID") @PathVariable Long teamId,
            @Valid @RequestBody TeamMessageRequest request) {

        try {
            // 获取当前用户ID
            Long userId = SecurityUtils.getCurrentUserId();

            // 设置团队ID
            request.setTeamId(teamId);

            // 发送消息
            TeamMessageDTO message = teamMessageService.sendMessage(request, userId);

            logger.info("团队消息发送成功 teamId={}, userId={}, messageId={}",
                       teamId, userId, message.getId());

            return ApiResponse.success("消息发送成功", message);

        } catch (Exception e) {
            logger.error("发送团队消息失败 teamId={}", teamId, e);
            return ApiResponse.error("发送消息失败: " + e.getMessage());
        }
    }

    /**
     * 获取团队消息历史（分页）
     */
    @GetMapping
    @Operation(summary = "获取团队消息历史", description = "分页获取团队聊天室的历史消息")
    public ApiResponse<Map<String, Object>> getMessages(
            @Parameter(description = "团队ID") @PathVariable Long teamId,
            @Parameter(description = "页码，从0开始") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小，最大100") @RequestParam(defaultValue = "20") int size) {

        try {
            // 获取当前用户ID
            Long userId = SecurityUtils.getCurrentUserId();

            // 获取消息历史
            Page<TeamMessageDTO> messages = teamMessageService.getTeamMessages(teamId, userId, page, size);

            logger.info("获取团队消息历史成功 teamId={}, userId={}, page={}, size={}, total={}",
                       teamId, userId, page, size, messages.getTotalElements());

            return ApiResponse.success("获取消息历史成功", Map.of(
                "messages", messages.getContent(),
                "totalElements", messages.getTotalElements(),
                "totalPages", messages.getTotalPages(),
                "currentPage", messages.getNumber(),
                "hasNext", messages.hasNext(),
                "hasPrevious", messages.hasPrevious()
            ));

        } catch (Exception e) {
            logger.error("获取团队消息历史失败 teamId={}", teamId, e);
            return ApiResponse.error("获取消息历史失败: " + e.getMessage());
        }
    }

    /**
     * 获取团队最近消息
     */
    @GetMapping("/recent")
    @Operation(summary = "获取最近消息", description = "获取团队聊天室的最近消息")
    public ApiResponse<List<TeamMessageDTO>> getRecentMessages(
            @Parameter(description = "团队ID") @PathVariable Long teamId,
            @Parameter(description = "消息数量限制，最大50") @RequestParam(defaultValue = "10") int limit) {

        try {
            // 获取当前用户ID
            Long userId = SecurityUtils.getCurrentUserId();

            // 获取最近消息
            List<TeamMessageDTO> messages = teamMessageService.getRecentMessages(teamId, userId, limit);

            logger.info("获取团队最近消息成功 teamId={}, userId={}, limit={}, count={}",
                       teamId, userId, limit, messages.size());

            return ApiResponse.success("获取最近消息成功", messages);

        } catch (Exception e) {
            logger.error("获取团队最近消息失败 teamId={}", teamId, e);
            return ApiResponse.error("获取最近消息失败: " + e.getMessage());
        }
    }

    /**
     * 更新消息状态
     */
    @PutMapping("/{messageId}/status")
    @Operation(summary = "更新消息状态", description = "更新消息的发送状态")
    public ApiResponse<Void> updateMessageStatus(
            @Parameter(description = "团队ID") @PathVariable Long teamId,
            @Parameter(description = "消息ID") @PathVariable Long messageId,
            @RequestBody Map<String, String> statusRequest) {

        try {
            // 获取当前用户ID
            Long userId = SecurityUtils.getCurrentUserId();

            // 解析状态
            String statusStr = statusRequest.get("status");
            TeamMessage.MessageStatus status = TeamMessage.MessageStatus.valueOf(statusStr);

            // 更新消息状态
            teamMessageService.updateMessageStatus(messageId, status, userId);

            logger.info("更新消息状态成功 teamId={}, messageId={}, status={}, userId={}",
                       teamId, messageId, status, userId);

            return ApiResponse.success("消息状态更新成功");

        } catch (Exception e) {
            logger.error("更新消息状态失败 teamId={}, messageId={}", teamId, messageId, e);
            return ApiResponse.error("更新消息状态失败: " + e.getMessage());
        }
    }

    /**
     * 搜索团队消息
     */
    @GetMapping("/search")
    @Operation(summary = "搜索团队消息", description = "在团队聊天室中搜索包含关键词的消息")
    public ApiResponse<Map<String, Object>> searchMessages(
            @Parameter(description = "团队ID") @PathVariable Long teamId,
            @Parameter(description = "搜索关键词") @RequestParam String keyword,
            @Parameter(description = "页码，从0开始") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "20") int size) {

        try {
            // 获取当前用户ID
            Long userId = SecurityUtils.getCurrentUserId();

            // 搜索消息
            Page<TeamMessageDTO> messages = teamMessageService.searchMessages(teamId, userId, keyword, page, size);

            logger.info("搜索团队消息成功 teamId={}, userId={}, keyword={}, results={}",
                       teamId, userId, keyword, messages.getTotalElements());

            return ApiResponse.success("搜索消息成功", Map.of(
                "messages", messages.getContent(),
                "totalElements", messages.getTotalElements(),
                "totalPages", messages.getTotalPages(),
                "currentPage", messages.getNumber(),
                "keyword", keyword
            ));

        } catch (Exception e) {
            logger.error("搜索团队消息失败 teamId={}, keyword={}", teamId, keyword, e);
            return ApiResponse.error("搜索消息失败: " + e.getMessage());
        }
    }

    /**
     * 获取消息统计信息
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取消息统计", description = "获取团队聊天室的消息统计信息")
    public ApiResponse<Object> getMessageStatistics(
            @Parameter(description = "团队ID") @PathVariable Long teamId) {

        try {
            // 获取当前用户ID
            Long userId = SecurityUtils.getCurrentUserId();

            // 获取统计信息
            Object statistics = teamMessageService.getMessageStatistics(teamId, userId);

            logger.info("获取消息统计成功 teamId={}, userId={}", teamId, userId);

            return ApiResponse.success("获取统计信息成功", statistics);

        } catch (Exception e) {
            logger.error("获取消息统计失败 teamId={}", teamId, e);
            return ApiResponse.error("获取统计信息失败: " + e.getMessage());
        }
    }
}
